<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance();

const tableData = ref([])

const getImgUrl = (name) => {
  // 商品名与图片映射
  if (name === 'oppo' || name === '小米') return new URL(`../assets/images/phon1.png`, import.meta.url).href;
  if (name === 'vivo' || name === '三星') return new URL(`../assets/images/phon2.png`, import.meta.url).href;
  if (name === '苹果' || name === '魅族') return new URL(`../assets/images/phon3.png`, import.meta.url).href;
  return new URL(`../assets/images/user-default.png`, import.meta.url).href;
}

const getTableData = async () => {
  const data = await proxy.$api.getTableData();
  tableData.value = data.tableData.map(item => ({ ...item }));
}

const updatePrice = (item, value) => {
  if (value < 0) {
    ElMessage.error('价格不能为负数');
    return;
  }
  item.price = value;
  ElMessage.success('价格已更新');
}

const toggleStatus = (item) => {
  item.status = !item.status;
  ElMessage.success(item.status ? '已上架' : '已下架');
}

onMounted(() => {
  getTableData();
});
</script>

<template>
  <div class="mall-list">
    <el-row :gutter="20">
      <el-col :span="8" v-for="item in tableData" :key="item.name">
        <el-card shadow="hover" class="mall-card">
          <img :src="getImgUrl(item.name)" class="mall-img" />
          <div class="mall-info">
            <div class="mall-title">{{ item.name }}</div>
            <div class="mall-price">
              <span>价格：</span>
              <el-input-number v-model="item.price" :min="0" @change="val => updatePrice(item, val)" />
            </div>
            <div class="mall-status">
              <el-tag :type="item.status ? 'success' : 'info'">
                {{ item.status ? '已上架' : '已下架' }}
              </el-tag>
              <el-button size="small" @click="toggleStatus(item)">
                {{ item.status ? '下架' : '上架' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="less">
.mall-list {
  padding: 20px;
}
.mall-card {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.mall-img {
  width: 120px;
  height: 120px;
  object-fit: contain;
  margin-bottom: 16px;
}
.mall-info {
  width: 100%;
  text-align: center;
}
.mall-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.mall-price {
  margin-bottom: 8px;
}
.mall-status {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}
</style>